package com.org.manhu.chargehelper.custom;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.org.manhu.chargehelper.R;

import android.content.Context;
import android.graphics.drawable.ClipDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

/**
 * 电池 充电动画
 * @author Administrator
 * BatteryChargerAnimation  
 * com.batterycharger.animation.custom
 * 2015-2-7上午11:19:50
 */
public class BatteryCharger extends FrameLayout {

	private static ExecutorService executors ;//单一线程池
	private static final int MAX_PROGRESS = 10000;
	private ClipDrawable mClipDrawable;
	private int mProgress = 0;
	private boolean isRunning = false;
	private ImageView imageView;
	
	static {
		executors = Executors.newSingleThreadExecutor();
	}
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mHandler.removeMessages(0x123);
			mClipDrawable.setLevel(mProgress);
			}
		};
		

	
	public BatteryCharger(Context context) {
		this(context, null, 0);
	}

	public BatteryCharger(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public BatteryCharger(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	private void init(Context context) {
		View view = LayoutInflater.from(context).inflate(R.layout.custom_loading, null);
		addView(view);
		imageView = (ImageView) findViewById(R.id.iv_progress);
		mClipDrawable = (ClipDrawable) imageView.getDrawable();
	}
	
	//暂时未用到此方法
	public void setBackGround(int source){
		if(imageView != null ){
			imageView.setBackgroundResource(source);	
		}
	}

	/** 开始充电动画   */
	public void startChargerAnim() {
		if (!isRunning) {
			isRunning = true;
			startCharger();
		}
	}

	/** 结束充电动画   */
	public void stopChargerAnim() {
		if(isRunning){
			isRunning = false;
			mProgress = 0;
		}

	}

	/***   启动动画   */
	private void startCharger(){
		executors.execute(new Runnable() {
			
			@Override
			public void run() {
				while (isRunning) {
					if (mProgress > MAX_PROGRESS) {
						mProgress = 0;
					}
					mProgress += 80;
					mHandler.sendEmptyMessage(0x123);
					try {
						Thread.sleep(20);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
}
